#!/usr/bin/env python3
import argparse
import sys
import logging
from pathlib import Path

from .analyzer import (analyze_binary_dependencies,
                       analyze_library_compatibility, perform_symbol_check)
from .reporter import Reporter
from .database import get_or_build_package_database, RPM_CACHE_DIR, clear_cache, show_cache_info
from .exceptions import GoCompatCheckerError
from .utils import check_required_commands


def setup_logging(debug_mode=False):
    """设置日志配置"""
    class ColorFormatter(logging.Formatter):
        """带颜色的日志格式化器"""
        COLORS = {
            logging.DEBUG: '\033[37m',   # 白色
            logging.INFO: '\033[92m',    # 绿色
            logging.ERROR: '\033[91m',   # 红色
            logging.WARNING: '\033[93m',  # 黄色
            'RESET': '\033[0m',
        }

        def format(self, record):
            color = self.COLORS.get(record.levelno, self.COLORS['RESET'])
            reset = self.COLORS['RESET']
            msg = super().format(record)
            return f"{color}{msg}{reset}"

    handler = logging.StreamHandler()
    handler.setFormatter(ColorFormatter('%(message)s'))
    level = logging.DEBUG if debug_mode else logging.INFO
    logging.basicConfig(level=level, handlers=[handler])


def main():
    """主函数：解析参数并执行兼容性检查"""
    parser = argparse.ArgumentParser(
        description="Go Application Compatibility Checker",
        formatter_class=argparse.RawTextHelpFormatter
    )
    parser.add_argument("binary", type=Path, nargs='?',
                        help="Path to the Go application binary to analyze.")
    parser.add_argument("--debug", action="store_true",
                        help="Enable verbose logging for debugging.")
    parser.add_argument("--clear-cache", action="store_true",
                        help="Clear all cached data and exit.")
    parser.add_argument("--cache-info", action="store_true",
                        help="Show cache information and exit.")
    args = parser.parse_args()

    setup_logging(debug_mode=args.debug)

    # 处理缓存管理命令
    if args.clear_cache:
        clear_cache()
        return

    if args.cache_info:
        show_cache_info()
        return

    # 检查是否提供了二进制文件参数
    if not args.binary:
        parser.error(
            "binary argument is required unless using --clear-cache or --cache-info")

    try:
        check_required_commands()
        package_db, library_db, location_db = get_or_build_package_database()

        logging.debug("Stage 2: Analyzing Application & Checking Dependencies")
        dependencies = analyze_binary_dependencies(args.binary)

        mismatched_libs_report, rpms_for_symbol_check = (
            analyze_library_compatibility(dependencies, package_db, library_db)
        )

        missing_symbols_report = []
        if rpms_for_symbol_check:
            missing_symbols_report = perform_symbol_check(
                args.binary, rpms_for_symbol_check, location_db, RPM_CACHE_DIR)

            if mismatched_libs_report:
                logging.debug("Note: Symbol check results may contain false "
                              "positives due to version mismatched libraries")
        else:
            logging.debug("Stage 3: Skipping symbol check - no fully "
                          "matched libraries")

        reporter = Reporter(mismatched_libs_report, missing_symbols_report)
        reporter.print_report()

    except GoCompatCheckerError as exc:
        logging.error("错误: %s", exc)
        sys.exit(1)
    except KeyboardInterrupt:
        logging.info("\n用户中断操作")
        sys.exit(130)
    except Exception as exc:
        logging.error("未预期的错误: %s", exc)
        if args.debug:
            import traceback
            traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()
